# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         testcase_folder.py
# Description:  
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2020/12/27 下午8:26
# -------------------------------------------------------------------------------
from rest_framework import status
from rest_framework.mixins import UpdateModelMixin, DestroyModelMixin, CreateModelMixin
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet

from apps.BasicAuthService.models import Role
from apps.HttpAutoTestService.filters import TestcaseFolderFilter
from apps.HttpAutoTestService.models import TestcaseFolder, Testcase
from apps.HttpAutoTestService.serializers import TestcaseFolderListSerializer, TestcaseFolderSerializer

__all__ = ['TestcaseFolderListViewSet', 'TestcaseFolderViewSet']


class TestcaseFolderListViewSet(ReadOnlyModelViewSet):
    """
    用例夹列表
    """
    serializer_class = TestcaseFolderListSerializer
    filter_class = TestcaseFolderFilter
    pagination_class = None

    def get_queryset(self):
        user = self.request.user
        testcase_folders = TestcaseFolder.objects.filter(is_deleted=False).order_by('create_time').values(
            'id', 'name', 'parent', 'project', 'is_system', 'floor', 'remark')
        if not Role.objects.filter(code='SUPERADMIN', user=user, is_deleted=False):
            testcase_folders = testcase_folders.filter(project__members=user).distinct()
        return testcase_folders


class TestcaseFolderViewSet(CreateModelMixin, UpdateModelMixin, DestroyModelMixin, GenericViewSet):
    """
    用例夹创建、更新、删除
    """
    queryset = TestcaseFolder.objects.filter(is_deleted=False)
    serializer_class = TestcaseFolderSerializer

    def create(self, request, *args, **kwargs):
        user = request.user
        data = request.data
        parent = data.get('parent')
        if parent:
            parent_testcase_folder = TestcaseFolder.objects.filter(id=parent, is_deleted=False).first()
            if parent_testcase_folder.floor == 4:
                return Response(status=status.HTTP_200_OK, data={'status': 'fail', 'msg': '用例夹创建失败，原因：用例夹层级最多为4层'},
                                content_type='application/json')
            else:
                data['floor'] = parent_testcase_folder.floor + 1
        else:
            data['floor'] = 1
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        testcase_folder = serializer.save()
        testcase_folder.creator = user
        testcase_folder.save()
        headers = self.get_success_headers(serializer.data)
        return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)

    def destroy(self, request, *args, **kwargs):
        id = kwargs.get('pk')
        testcase_folder = TestcaseFolder.objects.get(id=id)
        testcase_folder.is_deleted = True
        testcase_folder.save()

        # 获取项目内置用例夹
        default_testcase_folder = TestcaseFolder.objects.filter(project_id=testcase_folder.project_id, is_system=True,
                                                                is_deleted=False).first()
        Testcase.objects.filter(testcase_folder_id=id, is_deleted=False).update(testcase_folder=default_testcase_folder)
        return Response(status=status.HTTP_204_NO_CONTENT)
